package com.wagn.eduservice.entity.excel.excelutil;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wagn.config.exceptionHandler.MyException;
import com.wagn.eduservice.entity.EduSubject;
import com.wagn.eduservice.entity.excel.excelentity.SubjectExcelEntity;
import com.wagn.eduservice.service.EduSubjectService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectExcelEntity> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //读取表头
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println(headMap);
    }

    //一行一行的读取excel,excelReadEntity为一行的内容
    @Override
    public void invoke(SubjectExcelEntity excelReadEntity, AnalysisContext analysisContext) {
        //如果excel为空则抛出错误
        if(excelReadEntity==null){
            throw new MyException(20001,"文件不存在");
        }else {
            try{
                //添加一级分类
                EduSubject exit0 = this.isExit0(eduSubjectService, excelReadEntity.getClassify1());
                if (exit0 == null) {
                    exit0 = new EduSubject();
                    exit0.setParentId("0");
                    exit0.setTitle(excelReadEntity.getClassify1());
                    eduSubjectService.save(exit0);
                }
                //添加二级分类
                String pid = exit0.getId();
                EduSubject exit1 = this.isExit1(eduSubjectService, excelReadEntity.getClassify2(), pid);
                if (exit1 == null) {
                    exit1 = new EduSubject();
                    exit1.setTitle(excelReadEntity.getClassify2());
                    exit1.setParentId(pid);
                    eduSubjectService.save(exit1);
                }
            }catch (Exception e){
                throw new MyException(20001,"文件模板不符");
            }

        }
    }

    //不能重复添加一级分类
    private EduSubject isExit0(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }

    //不能重复添加二级分类
    private EduSubject isExit1(EduSubjectService eduSubjectService,String name, String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
